package com.hangyutech.strelitzia.page;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Signature;

import java.sql.Connection;

/**
 * Created by Andy on 2019/5/21.
 */

@Intercepts(@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}))
public class MySQLPagingInterceptor extends AbstractPagingInterceptor {

    @Override
    protected String getSelectTotalSql(String targetSql) {

        StringBuilder sqlBuilder = new StringBuilder();

        sqlBuilder.append("select count(*) as _count from ( ");
        sqlBuilder.append(targetSql);
        sqlBuilder.append(" ) as _count_table");
        System.out.println("count sql:" + sqlBuilder.toString());
        return sqlBuilder.toString();
    }

    @Override
    protected String getSelectPagingSql(String targetSql, PagingBounds bounds) {
        StringBuilder sqlBuilder = new StringBuilder(targetSql);

        sqlBuilder.append(" limit ").append(bounds.getOffset()).append(",").append(bounds.getLimit());
        System.out.println("page sql:" + sqlBuilder.toString());
        return sqlBuilder.toString();
    }

}